package com.hps.demo.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.hps.demo.job.HelloSimpleJob;
import com.hps.demo.job.MySimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author heps
 * @since 2020/6/10 9:54
 */
@Configuration
public class JobConfig {

  @Value("${job.cron}")
  private String cron;

  @Value("${job.shardingTotalCount}")
  private int shardingTotalCount;

  @Value("${job.shardingItemParameters}")
  private String shardingItemParameters;

  @Value("${job.jobParameters}")
  private String jobParameters;

  @Autowired
  private ZookeeperRegistryCenter regCenter;

  @Bean
  public SimpleJob stockJob() {
    return new MySimpleJob();
  }

  @Bean SimpleJob helloJob() {
    return new HelloSimpleJob();
  }

  @Bean(initMethod = "init")
  public JobScheduler simpleJobScheduler(final SimpleJob stockJob) {
    return new SpringJobScheduler(stockJob, regCenter, getLiteJobConfiguration(stockJob.getClass(),
        cron, shardingTotalCount, shardingItemParameters, jobParameters));
  }

  @Bean(initMethod = "init")
  public JobScheduler helloSimpleJobScheduler(final SimpleJob helloJob) {
    return new SpringJobScheduler(helloJob, regCenter, getLiteJobConfiguration(helloJob.getClass(),
        cron, shardingTotalCount, shardingItemParameters, jobParameters));
  }


  private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass,
      final String cron,
      final int shardingTotalCount,
      final String shardingItemParameters,
      final String jobParameters) {
    // 定义作业核心配置
    JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount).
        shardingItemParameters(shardingItemParameters).jobParameter(jobParameters).build();
    // 定义SIMPLE类型配置
    SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, jobClass.getCanonicalName());
    // 定义Lite作业根配置
    LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(true).build();
    return simpleJobRootConfig;

  }
}
